<?php

namespace app\agent\controller;

use app\models\{Region, User as Users, Coupon, Car, AgentArea, Agent, IntergralLog, Product, Order};
use think\Db;
use think\Validate;

class User extends Base
{

    public function index()
    {
        if ($this->request->isAjax()) {
            //获取合伙人身份
            $user_id = (new Order())->where('agentid', $this->request->agent['id'])->where(['status' => [4]])->column('user_id');
            $model = new Users();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['nickName|mobile', 'like', '%' . $post['title'] . '%'];
            }
            $where[] = ['id', 'in', $user_id];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $result) {
                $address = (new Car())->where('user_id', $result['id'])->order('is_default desc')->find() ?? [];
                $result['address'] = $address;
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }


    public function interlog()
    {
        if ($this->request->isAjax()) {
            $model = new IntergralLog();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('id/d') ?? 0;
            $where = array();
            $where[] = ['user_id', '=', $user_id];
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function sendcoupon2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require',
                'days' => 'require|gt:0',
                'productid' => 'require'
            ], [
                'user_id.require' => '用户ID不能为空',
                'days.require' => '有效期不能为空',
                'productid.require' => '可用项目不能为空',
                'days.gt' => '有效期必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['agentid'] = $this->request->agent['id'];
            $number = (int)$data['number'] ?? 1;
            $coupon = [];
            for ($i = 0; $i < $number; $i++) {
                $coupon[] = [
                    'user_id' => $data['user_id'],
                    'agentid' => $data['agentid'],
                    'type' => 1,
                    'types' => 2,
                    'modelcount' => count($data['carmodel']),
                    'productid' => implode(',', $data['productid']),
                    'carmodel' => implode(',', $data['carmodel']),
                    'text' => '赠送',
                    'endtime' => date('Y-m-d H:i:s', time() + $data['days'] * 86400)
                ];
            }
            $res = (new Coupon())->allowfield(true)->saveAll($coupon);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 200, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('user_id/d', 0);
            return view('', [
                'id' => $id
            ]);
        }
    }

    public function coupon()
    {
        if ($this->request->isAjax()) {
            $model = new Coupon();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $user_id = input('user_id/d', 0);
            $promo = input('promo/d', 0);
            $where = array();
            $where[] = ['agentid', '=', $this->request->agent['id']];
            if (!empty($user_id)) {
                $where[] = ['user_id', '=', $user_id];
            }
            if (!empty($promo)) {
                $where[] = ['promo', '=', $promo];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $result) {
                $result['product_name'] = '--';
                $result['car_name'] = '--';
                if ($result['types'] == 2) {
                    $result['product_name'] = '';
                    $typess = explode(',', $result['productid']);
                    foreach ($typess as $k => $types) {
                        $type_text = config()['config']['type'][$types] ?? '';
                        if ($k == 0 && empty($result['product_name'])) {
                            $result['product_name'] = $type_text;
                        }
                        if ($k >= 1) {
                            $result['product_name'] = $result['product_name'] . '、' . $type_text;
                        }
                    }
                    $result['car_name'] = '';
                    $typess2 = explode(',', $result['carmodel']);
                    foreach ($typess2 as $k => $types) {
                        $type_texts = config()['config']['carmodel'][$types] ?? '';
                        if ($k == 0 && empty($result['car_name'])) {
                            $result['car_name'] = $type_texts;
                        }
                        if ($k > 0) {
                            $result['car_name'] = $result['car_name'] . '、' . $type_texts;
                        }
                    }
                }
                $result['usernick'] = (new Users())->where('id', $result['user_id'])->value('nickName');
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    // public function couponel()
    // {
    //     if ($this->request->isPost()) {
    //         $id = $this->request->post('id/d', 0);
    //         if (empty($id)) {
    //             return json(['code' => 1, 'msg' => '请选择删除项目']);
    //         }
    //         $banner = (new Coupon())->where(['id' => $id, 'agentid' => $this->request->agent['id']])->find();
    //         if (empty($banner)) {
    //             return json(['code' => 1, 'msg' => '优惠券不存在，请重试']);
    //         }
    //         if ($banner['status'] != 1) {
    //             return json(['code' => 1, 'msg' => '优惠券已作废']);
    //         }
    //         $res = (new Coupon())->where('id', $id)->update(['status' => 2, 'remark' => $banner['remark'] . '|管理员作废']);
    //         if ($res) {
    //             return json(['code' => 200, 'msg' => '操作成功']);
    //         }
    //         return json(['code' => 1, 'msg' => '操作失败']);
    //     }
    // }


    public function couponel()
    {
        $id = input('id');
        $agentid = $this->request->agent['id'];
        $ids = [];
        if (!empty($id)) {
            $model = new Coupon();
            if (is_array($id)) {
                foreach ($id as $idd) {
                    $cate = $model->where(['id' => $idd, 'status' => 1, 'agentid' => $agentid])->find();
                    if (!empty($cate)) {
                        $ids[] = $idd;
                    }
                }
            } else {
                $cate = $model->where(['id' => $id, 'status' => 1, 'agentid' => $agentid])->find();
                if (!empty($cate)) {
                    $ids[] = $id;
                }
            }
            if (count($ids) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '非审核状态或无可操作内容']);
            }
            foreach ($ids as $id) {
                Db::startTrans();
                try {
                    $model->where('id', $id)->update(['status' => 3, 'remark' => '作废']);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function sendcoupon()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'getmoney' => 'require|gt:0',
                'money' => 'require|gt:0',
                'user_id' => 'require',
                'days' => 'require|gt:0',
            ], [
                'getmoney.require' => '可用金额不能为空',
                'getmoney.gt' => '可用金额必须大于0',
                'money.require' => '抵扣金额不能为空',
                'money.gt' => '抵扣金额必须大于0',
                'user_id.require' => '用户ID不能为空',
                'days.require' => '有效期不能为空',
                'days.gt' => '有效期必须大于0',

            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['type'] = 2;
            $data['agentid'] = $this->request->agent['id'];
            // if ($data['getmoney'] < $data['money']) {
            //     return json(['code' => 1, 'msg' => '抵扣金额不能超过可用金额']);
            // }
            $data['endtime'] = date('Y-m-d H:i:s', time() + $data['days'] * 86400);
            $res = (new Coupon())->allowfield(true)->save($data);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 200, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('user_id/d', 0);
            return view('', [
                'id' => $id
            ]);
        }
    }
}
